<?php

/**
 * This file is accessed through JavaScript and executes code on the server side (AJAX).
 * 
 * @author Siim Loog
 */

session_start();
require_once 'init.php';

if ( !isset($_POST['action']) ) {
	exit;
}

if(empty($_SESSION)){
	echo "LoggedOut";
	exit;
} 

switch( $_POST['action'] ) {
	case 'insertProblem':
		if(!isset($_SESSION['oppejoud'])){
					exit;
				}
		$vastus = htmlentities($_POST['vastus']);
		$vastus2 = htmlentities($_POST['vastus2']);
		$vastus3 = htmlentities($_POST['vastus3']);
		$argumendid = $_POST['argumendid'];
		$kirjeldus = $_POST['kirjeldus'];
		$punkte = $_POST['punktid'];
		$kontrolltoo = $_POST['testId'];
		//echo "vastuseks seatud: ".html_entity_decode($vastus)."<br/>";
		if(Problem::insert($sql, $vastus, $vastus2, $vastus3, $argumendid , $kirjeldus, $punkte, $kontrolltoo )){
			echo "Ulesanne edukalt salvestatud<br/>";
			echo "vastuseks seatud: ".html_entity_decode($vastus)."<br/>";
		} else echo "Ulesannet ei saanud salvestada. Proovi uuesti.";
		break;

		
		
	case 'getProblemArea':
		echo $site->fetch( 'centerarea/enterProblem.html' );
		break;
		
	case 'getCorrect':
		$questionId = $_POST['question'];
		$result = Problem::arguments($sql, $questionId);
		echo $result[0]['argumendid'];
		break;
	
	case 'alterProblem':
		if(!isset($_SESSION['oppejoud'])){
					exit;
				}
		$questionId = $_POST['question'];
		$answer1 = $_POST['answer1'];
		$answer2 = $_POST['answer2'];
		$answer3 = $_POST['answer3'];
		$points = $_POST['points'];
		$arguments = $_POST['arguments'];
		$description = $_POST['description'];
		$result = Problem::alterProblem($sql, $questionId, $answer1,
										$answer2,$answer3,$points,
										$arguments,$description);
		if($result){
			echo "OK";
		}else echo "Error";
		break;
		
	case 'removeProblem':
		if(!isset($_SESSION['oppejoud'])){
					exit;
				}
		$questionId = $_POST['question'];
		$result = Problem::removeQuestion($sql, $questionId);
		if($result){
			echo "OK";
		}else echo "Error";
		break;
		
	case 'loadProblemData':
		if(!isset($_SESSION['oppejoud'])){
					exit;
				}
		$problem = Problem::testProblemDescription($sql);
		//print_r($problem);
		if($result){
			foreach($problem as $a){
				echo "<p>Kirjeldus: ";
				echo "".$a['tekst']."";
				echo "<br />Argumendid: ".$a['argumendid']."";
				echo "<br />Vastus: ".html_entity_decode($a['vastus'])."";
				echo "<br />";
			}
		}
		break;
		

}
	
?>
